<template>
  <el-dialog
    :title="lang.t('page.account.erp.title')"
    v-model="show"
    :width="400"
    destroy-on-close
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
      <el-form-item :label="lang.t('page.account.erp.username')" prop="username">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item :label="lang.t('page.account.erp.password')" prop="password">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
    </el-form>
    <el-button style="width: 100%" type="primary" @click="onLogin">{{ lang.t('page.account.erp.btn') }}</el-button>
    <el-alert
      type="warning"
      :description="lang.t('page.account.erp.message.tips')"
      :closable="false"
      style="margin-top: 20px"
    />
  </el-dialog>
</template>
<script>
import { ref } from 'vue'
import app from '@/app'
import storage from '@/app/storage'
import accountModel from '@/model/account'

export default {
  setup() {
    // 对话框
    const show = ref(false)

    // 表单
    const form = ref({})
    const formRef = ref()
    const rules = {
      username: [
        { required: true, message: ' ', trigger: 'blur' }
      ],
      password: [
        { required: true, message: ' ', trigger: 'blur' }
      ]
    }

    // 打开
    const open = () => {
      show.value = true
      const erp = storage.get('erp')
      form.value = erp ? erp : {}
    }

    // 更新
    const onLogin = () => {
      formRef.value.validate(valid => {
        if (valid) {
          storage.set('erp', form.value)
          app.ui.message('success', 'ok') 
          show.value = false
          app.window.newWin(
            process.env.VUE_APP_ERP_URL + '/?' + Date.now() + '#/' +
            '?number=' + accountModel.getUser().number + 
            '&username=' + form.value.username + 
            '&password=' + form.value.password
          )
        }
      })
    }

    return {
      lang: app.lang,
      show,
      open,
      form,
      formRef,
      rules,
      onLogin
    }
  }
}
</script>